var lastTotalCnt, lastTotalPage;
var saveFlag;
var deleteFlag;
var duplicateLoginFlag = false;

function clearTable(tableID) {
	var table = document.getElementById(tableID);
	var rows = table.rows && table.rows.length;
	for (var i = 1; i <= rows; i++) {
		table.deleteRow(0);
	}
}
/*千位分隔符*/
function ThousandsSeparator(num){
	  num = num+"";
	  if(/^.*\..*$/.test(num)){
	   var pointIndex =num.lastIndexOf(".");
	   var intPart = num.substring(0,pointIndex);
	   var pointPart =num.substring(pointIndex+1,num.length);
	   intPart = intPart +"";
	    var re =/(-?\d+)(\d{3})/
	    while(re.test(intPart)){
	     intPart =intPart.replace(re,"$1,$2")
	    }
	   num = intPart+"."+pointPart;
	  }else{
	   num = num +"";
	    var re =/(-?\d+)(\d{3})/;
	    while(re.test(num)){
	     num =num.replace(re,"$1,$2")
	    }
	  }
	  return num;
	}
function round(v,e){
	var t = 1;
	for(;e>0;t*=10,e--);
	for(;e<0;t/=10,e++);
	return Math.round(v*t)/t;
}
function floor(v,e){
	var t = 1;
	for(;e>0;t*=10,e--);
	for(;e<0;t/=10,e++);
	return Math.floor(v*t)/t;
}
function addDay(date, days){
	var intDays = parseInt(days, 10);
	if (!isNaN(intDays)) {
		return date.setDate(date.getDate() + intDays);
	} else {
		return date;
	}
}
function stringToDate(date, symbol){
	if(date.length <= 10){
		if (!symbol) {
			symbol = "-";
		}
		var array = date.split(symbol);
		return new Date(array[0], array[1] - 1, array[2]);
	} else {
		var array = date.split(/[^0-9]/ig);
		return new Date(array[0], array[1] - 1, array[2], array[3] || 0, array[4] || 0, array[5] || 0);
	}
}
//数据库日期转化为JSON在页面显示
function date2String(time){
	if (time) {
		var datetime = getSystemTime();
	    datetime.setTime(time);
	    var year = datetime.getFullYear();
	    var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
	    var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();;
	    return year + "-" + month + "-" + date;
	}
}

//数据库时间转化为JSON在页面显示
function timeStamp2String(time, model){
	 if (time) {
		 var datetime = getSystemTime();
		 datetime.setTime(time);
		 var year = datetime.getFullYear();
		 var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : "" + (datetime.getMonth() + 1);
		 var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : "" + datetime.getDate();
		 var hour = datetime.getHours()< 10 ? "0" + datetime.getHours() : "" + datetime.getHours();
		 var minute = datetime.getMinutes()< 10 ? "0" + datetime.getMinutes() : "" + datetime.getMinutes();
		 var second = datetime.getSeconds()< 10 ? "0" + datetime.getSeconds() : "" + datetime.getSeconds();
		 if (model == 1) {
			 return year + month + date + hour + minute + second;
		 } else {
			 return year + "-" + month + "-" + date +" "+ hour + ":" + minute + ":" + second;
		 }
	 }
}
function time2String(time, model){
	 if (time) {
		 var datetime = getSystemTime();
		 datetime.setTime(time);
		 var hour = datetime.getHours()< 10 ? "0" + datetime.getHours() : "" + datetime.getHours();
		 var minute = datetime.getMinutes()< 10 ? "0" + datetime.getMinutes() : "" + datetime.getMinutes();
		 var second = datetime.getSeconds()< 10 ? "0" + datetime.getSeconds() : "" + datetime.getSeconds();
		 if (model == 1) {
			 return hour + minute + second;
		 } else {
			 return hour + ":" + minute + ":" + second;
		 }
	 }
}
function formatTime(time) {
	if (time) {
		var second = parseInt(time, 10); // 秒
	    var minute  = 0; // 分
	    var hour = 0; // 时
	    if(second > 60) {
	    	minute = parseInt(second / 60, 10);
	    	second = second % 60;
	        if(minute > 60) {
	        	hour = parseInt(minute / 60, 10);
	        	minute = minute % 60;
	        	return hour + "小时" + minute + "分" + second + "秒";
	        } else {
	        	return minute + "分" + second + "秒";
	        }
	    } else {
	    	return second + "秒";
	    }
	}
}

function checkAll(checkboxName) {
	var checkbox = document.getElementsByName(checkboxName);
	var length = checkbox && checkbox.length || 0;
	for (i = 0; i < length; i++) {
		if (!checkbox[i].disabled) {
			checkbox[i].checked = event.srcElement.checked;
		}
	}
}

function getCheckbox(checkboxName) {
	var checkbox = {
		count: 0,
		row_index: []
	};
	var checkboxName = document.getElementsByName(checkboxName);
	var length = checkboxName && checkboxName.length || 0;
	for (i = 0; i < length; i++) {
		if (checkboxName[i] && checkboxName[i].checked == true) {
			checkbox.count += 1;
			checkbox.row_index.push(i);
		}
	}
	return checkbox;
}

function getCheckDataList(data, ID) {
	var checkbox = getCheckbox("chk");
	var count = checkbox && checkbox.count || 0;
	var index = undefined;
	var dataList = [];
	for (var i=0; i<count; i++) {
		index = checkbox && checkbox.row_index[i] || 0;
		dataList.push(data && data[index] && data[index][ID]);
	}
	return dataList.toString();
}

function showMessge(message, model, callback) {
	model = model == undefined ? "model1" : model;
	$('#message', parent.document).html(message || '提示消息未设置！');
	$('#model1', parent.document).hide();
	$('#model2', parent.document).hide();
	$('#model3', parent.document).hide();
	$("#" + model, parent.document).show();
	$('#close1', parent.document).hide();
	$('#close3', parent.document).hide();
	if (model == "model3") {
		$('#close3', parent.document).show();
	} else {
		$('#close1', parent.document).show();
	}
	if ($('.modal-backdrop.fade.in').length > 0) {
		setTimeout(setMessageModal, 500);
	} else {
		setMessageModal();
	}
	
	if (typeof callback === 'function') {
		$('#myMessageModal', parent.document).on('shown.bs.modal', function (e) {
			callback();
		});
	}
}
function setMessageModal() {
	$('#myMessageModal', parent.document).modal('show');
}
function hideMessge() {
	$('#myMessageModal', parent.document).modal('hide');
}
function showLoading() {
	$('#loadingModal', parent.document).modal('show');
}

function hideLoading() {
	$('#loadingModal', parent.document).modal('hide');
}

function getRootPath() {
	var href = window.document.location.href;
	var pathName = window.document.location.pathname;
	var index = href.indexOf(pathName);
	var localhostPaht = href.substring(0, index);
	var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
	if (projectName != "/BalanceProject") {
		projectName = "";
	}
	return(localhostPaht + projectName + '/');
}

function setBaseUrl() {
	var base = document.getElementsByTagName("base");
	if (base && base[0]) {
		base[0].href = getRootPath();
	}
}

function createAjax() {
	this.url = '';
	this.type = '';
	this.data = {};
	this.dataType = '';
	this.timeout;
	this.success = function() {
	};
	this.error = function() {
	};
};

function startAjax(ajax) {
	var options = {
			type : ajax.type,
			url : ajax.url,
			data : ajax.data,
			dataType : 'json',
			timeout : ajax.timeout,
			success : ajax.success,
			error : ajax.error
		};
	return $.ajax(options);
}

//清空form表单
function formReset(formID){
	document.getElementById(formID).reset();
}
function selectDate(ID, minView, pickerPosition, startView){
	$('#' + ID).datetimepicker({
        language: 'zh-CN', // String. 默认值: 'en'
        weekStart: 1, // Integer. 默认值：0;一周从哪一天开始。0（星期日）到6（星期六）
        todayBtn:  "linked", // Boolean, "linked". 默认值: false;
        todayHighlight: true, // Boolean. 默认值: false;如果为true, 高亮当前日期。
        autoclose: true, // Boolean. 默认值：false;当选择一个日期之后是否立即关闭此日期时间选择器。
        startView: startView == undefined ? 2 : startView, // Number, String. 默认值：2, 'month';日期时间选择器打开之后首先显示的视图。[0/'hour',1/'day',2/'month',3/'year',4/'decade']
        minView: minView == undefined ? 2 : minView, // Number, String. 默认值：0, 'hour';日期时间选择器所能够提供的最精确的时间选择视图。
        forceParse: true, // Boolean. 默认值: true;当选择器关闭的时候，是否强制解析输入框中的值
        pickerPosition: pickerPosition || 'bottom-left', // String. 默认值: 'bottom-right';通过设置选项可以讲选择器放倒输入框下方
    });
}

function selectDateTime(ID, minView, pickerPosition, startView){
	$('#' + ID).datetimepicker({
        language: 'zh-CN', // String. 默认值: 'en'
        weekStart: 1, // Integer. 默认值：0;一周从哪一天开始。0（星期日）到6（星期六）
        todayBtn:  "linked", // Boolean, "linked". 默认值: false;
        todayHighlight: true, // Boolean. 默认值: false;如果为true, 高亮当前日期。
        autoclose: true, // Boolean. 默认值：false;当选择一个日期之后是否立即关闭此日期时间选择器。
        startView: startView == undefined ? 2 : startView, // Number, String. 默认值：2, 'month';日期时间选择器打开之后首先显示的视图。[0/'hour',1/'day',2/'month',3/'year',4/'decade']
        minView: minView == undefined ? 0 : minView, // Number, String. 默认值：0, 'hour';日期时间选择器所能够提供的最精确的时间选择视图。
        forceParse: true, // Boolean. 默认值: true;当选择器关闭的时候，是否强制解析输入框中的值
        pickerPosition: pickerPosition || 'bottom-left', // String. 默认值: 'bottom-right';通过设置选项可以讲选择器放倒输入框下方
    });
}
function removeDate(ID){
	$('#' + ID).datetimepicker('remove');
}
function selectFile(inputID, data, callback){
	var $element = $('#' + inputID);
	var option = {
        language: 'zh', //设置语言
        maxFileCount: 1,
        maxFilePreviewSize: 0
	}
	$.extend(true, option, data);
	$element.fileinput(option)
		.on('fileuploaded', 
			function(event, data, previewId, index){
				var result = data && data.response && data.response.result;
				if (result == "Success") {
					showMessge("上传成功！");
					if (typeof callback === 'function') {
						var inputFile = document.getElementById(inputID) || {};
						var data = {
							file: 	inputFile.files || [],
							index: option && option.index,
							flag: "uploaded"
						}
						callback(data);
					}
				}
				
			})
	    .on('filedeleted', 
			function(event, key, data, extraData){
				var result = data && data.responseJSON && data.responseJSON.result;
				if (result == "Success") {
					showMessge("删除成功！");
					if (typeof callback === 'function') {
						var inputFile = document.getElementById(inputID) || {};
						var data = {
							file: 	extraData && extraData.fileName,
							index: option && option.index,
							flag: "delete"
						}
						callback(data);
					}
				}
	    	})
	    .on('filecleared', 
			function(event, key, data, extraData){
	    		callback();
			});
}
function showImage(ImageOne, ImageTwo, object){
	if (ImageOne) {
		$('#' + ImageOne).show();
	}
	if (ImageTwo) {
		$('#' + ImageTwo).hide();
	}
}
function setMap(position, containerID, zoom, mapStyle) {
	containerID = containerID || 'container';
	var map = new AMap.Map(containerID, {
       resizeEnable: true,
       zoom: zoom || 11,
//       center: position && position.length > 0 ? position : [116.3391, 39.95]
       center: position && position.length > 0 ? position : [116.396869, 39.915]
	});
	// 默认样式:normal, 深色样式:dark, 夜空蓝样式:blue_night, 浅色样式:fresh, osm清新风格样式:light
	map.setMapStyle(mapStyle || "normal");
	map.on('indoor_create',function(){
		// 关闭楼层切换
		map.indoorMap && map.indoorMap.hideFloorBar();
	});
	/*AMap.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.OverView', 'AMap.Geolocation', 'AMap.MapType'],
		function(){
			// 工具条(缩放、平移、定位等功能按钮)
			//map.addControl(new AMap.ToolBar());
			// 比例尺(展示地图在当前层级和纬度下的比例尺)
			//map.addControl(new AMap.Scale());
			// 鹰眼(在地图右下角显示地图的缩略图)
			//map.addControl(new AMap.OverView({isOpen:true}));
			// 定位(用来获取和展示用户主机所在的经纬度位置)
			//map.addControl(new AMap.Geolocation());
			// 类别切换(实现默认图层与卫星图、实施交通图层之间切换的控)
			//map.addControl(new AMap.MapType());
	});*/
	return map;
}

function setPieStatus(seriesName, data, radius, subtext, titleText, strFrormatter){
	option = {
		    tooltip: {
			        trigger: 'item',
			        formatter: strFrormatter || "{a} <br/>{b} ({d}%)"
			},
		    title: {
		        text: titleText || '',
		        subtext: subtext || '',
//			        itemGap: 10 , 副标题与标题之间的距离
		         normal: {
	                    show: false,
	                    position: 'center'
		                },
                textStyle: {
                    color:'#18BFD3',
                    fontSize: '40',
                },
	            subtextStyle: {
	                color: 'black',// 副标题文字颜色
	            },
		        x: 'center',
		        y: 'center'
		    },
		    series: [
		        {
		            name: seriesName,
		            type:'pie',
		            radius: radius || ['30%', '45%'],
		            label: { //显示与隐藏线与内容
		                normal: {
		                    show: false,
		                    position: 'center'
		                },
		            },
		            data: data
		        }
		    ]
		};
		// 使用刚指定的配置项和数据显示图表。
		return option;
}

function searchEcharts(orient, position, legendBottom, legendData, seriesName, data, radius, subtext
		, titleText, strFrormatter, textColor, titleSize, subtextColor, subtextSize, titlex, titley){
	option = {
		 tooltip: {
		        trigger: 'item',
		        formatter: strFrormatter || "{a} <br/>{b} ({d}%)"
		    },
		    title: {
		        text: titleText || '',
		        subtext: subtext || '',
		        textStyle : {
		            color: textColor || 'black',
		            fontSize: titleSize || '',
		        },
		         normal: {
		                    show: false,
		                    position: 'center'
		                },
	            subtextStyle: {
	                color: subtextColor || 'black',// 副标题文字颜色
	                fontSize: subtextSize || '',
	            },
		        x: titlex || 'center',
		        y: titley || 'center'
		   },
	    legend: {
	        orient: orient,//horizontal横排 vertical竖排
	        x: position || 'center',
			y: legendBottom || 'center',
	        data: legendData
	    },
	    series: [
	        {
	            name: seriesName,
	            type:'pie',
	            radius: radius || ['30%', '45%'],
	            data: data
	        }
	    ]
	};
	// 使用刚指定的配置项和数据显示图表。
	return option;
}
function echartStyle(normalColor, labelFlag, lineFlag, emphasisColor, labelLineLength){
	var style = {
		    normal : {
		        color: normalColor,
		        label: {show:labelFlag},//是否显示文字
		        labelLine: {
		        	show:lineFlag,
		        	length: labelLineLength || undefined, //显示线的长度
		        	},//是否显示线
		    }, 
		    emphasis : {//指向变颜色
		        color: emphasisColor
		    }
		};
	return style;
}
function downloadFile(url) {
	var iframe = document.getElementsByTagName("iframe");
	if(!iframe || iframe.length == 0) {
		iframe = document.createElement("iframe");
		iframe.src = url;
	    iframe.style.display = "none";
	    document.body.appendChild(iframe);
	} else {
		iframe[0].src = url;
	}
//	window.open(url);
}
function $ajaxSubmit(formID, url, callback, data) {
	$("#" + formID).ajaxSubmit({
		url : url,
		type : 'post',
		dataType : 'json',
		data: data,
		resetForm: "true",
		success : function(data) {
			if (typeof callback === 'function') {
				callback(data);
			}
		},
		error : function(data) {
			setTimeout(hideLoading, 500);
			if (data.status == "403" && data.statusText == "Forbidden") {
				showMessge(messageContent["Access.Forbidden"]);
			} else {
				if (duplicateLoginFlag) {
					showMessge(messageContent["Login.DuplicateLogin"], "model3");
				} else {
					if (data.responseText) {
						if (data.responseText.indexOf("duplicateLogin") >= 0) {
							showMessge(messageContent["Login.DuplicateLogin"], "model3");
							duplicateLoginFlag = true;
						} else if (data.responseText.indexOf("loginTimeout") >= 0) {
							showMessge(messageContent["Login.Timeout"], "model3");
						}
					} else {
						showMessge(messageContent["Access.Failed"]);
					}
				}
			}
		},
		timeout: function(data){
			setTimeout(hideLoading, 500);
			showMessge(messageContent["Access.Timeout"]);
		}
	})
}
function $ajaxFile(url, callback, data, dataType, type) {
	$.ajax({
		url : url,
		type : type || 'post',
		dataType : dataType || 'json',
		data: data,
		cache: false,  
		contentType: false,  
		processData: false,
		success : function(data) {
			if (typeof callback === 'function') {
				callback(data);
			}
		},
		error : function(data) {
			setTimeout(hideLoading, 500);
			if (data.status == "403" && data.statusText == "Forbidden") {
				showMessge(messageContent["Access.Forbidden"]);
			} else {
				if (duplicateLoginFlag) {
					showMessge(messageContent["Login.DuplicateLogin"], "model3");
				} else {
					if (data.responseText) {
						if (data.responseText.indexOf("duplicateLogin") >= 0) {
							showMessge(messageContent["Login.DuplicateLogin"], "model3");
							duplicateLoginFlag = true;
						} else if (data.responseText.indexOf("loginTimeout") >= 0) {
							showMessge(messageContent["Login.Timeout"], "model3");
						}
					} else {
						showMessge(messageContent["Access.Failed"]);
					}
				}
			}
		},
		timeout: function(data){
			setTimeout(hideLoading, 500);
			showMessge(messageContent["Access.Timeout"]);
		}
	})
}
function $ajaxCommon(url, callback, data, dataType, type) {
	$.ajax({
		url : url,
		type : type || 'post',
		dataType : dataType || 'json',
		data: data,
		success : function(data) {
			if (typeof callback === 'function') {
				callback(data);
			}
		},
		error : function(data) {
			setTimeout(hideLoading, 500);
			if (data.status == "403" && data.statusText == "Forbidden") {
				showMessge(messageContent["Access.Forbidden"]);
			} else {
				if (duplicateLoginFlag) {
					showMessge(messageContent["Login.DuplicateLogin"], "model3");
				} else {
					if (data.responseText) {
						if (data.responseText.indexOf("duplicateLogin") >= 0) {
							showMessge(messageContent["Login.DuplicateLogin"], "model3");
							duplicateLoginFlag = true;
						} else if (data.responseText.indexOf("loginTimeout") >= 0) {
							showMessge(messageContent["Login.Timeout"], "model3");
						}
					} else {
						showMessge(messageContent["Access.Failed"]);
					}
				}
			}
		},
		timeout: function(data){
			setTimeout(hideLoading, 500);
			showMessge(messageContent["Access.Timeout"]);
		}
	})
}
function $ajaxList(url, callback, data) {
	$.ajax({
		url : url,
		type : 'post',
		dataType : 'json',
		data : data,
		success : function(data) {
			if (typeof callback === 'function') {
				callback(data);
			}
		},
		error : function(data) {
			if (data.status == "403" && data.statusText == "Forbidden") {
				showMessge(messageContent["Access.Forbidden"]);
			} else {
				if (duplicateLoginFlag) {
					showMessge(messageContent["Login.DuplicateLogin"], "model3");
				} else {
					if (data.responseText) {
						if (data.responseText.indexOf("duplicateLogin") >= 0) {
							showMessge(messageContent["Login.DuplicateLogin"], "model3");
							duplicateLoginFlag = true;
						} else if (data.responseText.indexOf("loginTimeout") >= 0) {
							showMessge(messageContent["Login.Timeout"], "model3");
						}
					} else {
						showMessge(messageContent["Access.Failed"]);
					}
				}
			}
		},
	})
}
function $ajax(getUrl, getData, callback, callCheck, errorCallback) {
	if (typeof callCheck === 'function') {
		if (!callCheck()) return;
	}
	var url = undefined;
	if (typeof getUrl === 'function') {
		url = getUrl();
	} else {
		url = getUrl;
	}
	if (url == undefined) {
		if (typeof callback === 'function') {
			callback();
		}
		return;
	}
	var data = undefined;
	if (typeof getData === 'function') {
		data = getData();
	} else if (typeof getData === 'string') {
		data = $("#" + getData).serialize();
	} else {
		data = getData;
	}
	if (typeof errorCallback !== 'function') {
		showLoading();
	}
	$.ajax({
		url : url,
		type : 'post',
		dataType : 'json',
		data : data,
		success : function(data) {
			if (typeof errorCallback !== 'function') {
				setTimeout(hideLoading, 500);
			}
			if (typeof callback === 'function') {
				callback(data);
			}
		},
		error : function(data) {
			if (typeof errorCallback === 'function') {
				errorCallback("error");
			} else {
				setTimeout(hideLoading, 500);
				if (data.status == "403" && data.statusText == "Forbidden") {
					showMessge(messageContent["Access.Forbidden"]);
				} else {
					if (duplicateLoginFlag) {
						showMessge(messageContent["Login.DuplicateLogin"], "model3");
					} else {
						if (data.responseText) {
							if (data.responseText.indexOf("duplicateLogin") >= 0) {
								showMessge(messageContent["Login.DuplicateLogin"], "model3");
								duplicateLoginFlag = true;
							} else if (data.responseText.indexOf("loginTimeout") >= 0) {
								showMessge(messageContent["Login.Timeout"], "model3");
							}
						} else {
							showMessge(messageContent["Access.Failed"]);
						}
					}
				}
			}
		},
		timeout: function(data){
			if (typeof errorCallback === 'function') {
				errorCallback("timeout");
			} else {
				setTimeout(hideLoading, 500);
				showMessge(messageContent["Access.Timeout"]);
			}
		}
	});
}
function createTableHead(tableHeadID, table, callbackSearch) {
	var thead = $("#" + tableHeadID);
	var $tr = $('<tr>').appendTo(thead);
	var length = table.length;
	for(var i=0; i<length; i++){
		if (table[i].tableDisplay) {
			if (table[i].headerNameEN == "checkbox") {
				$("<th>").addClass("chkwidth").html('<input id="chkAll" type="checkbox" onclick="checkAll(' + "'chk'" + ')">').appendTo($tr);
			} else if (table[i].headerNameEN == "number") {
				$("<th>").addClass("nowidth").html(table[i].headerNameCN).appendTo($tr);
			} else if(table[i].order){
				$("<th>").html('<a onclick="order(1,\'' + table[i].headerNameEN + '\');"' + 'class="details">' + table[i].headerNameCN + '</a>' + "&nbsp;<div style='display:inline'>"+
				  '<img id="' + table[i].headerNameEN + 'Order0" name="' + table[i].headerNameEN + 'Order" src="static/images/asc.png" style="margin-top: -10px;cursor:pointer;" onclick="order(\'asc\',\'' + table[i].headerNameEN + '\');">' + 
				  '<img id="' + table[i].headerNameEN + 'Order1" name="' + table[i].headerNameEN + 'Order" src="static/images/desc.png" style="margin-top: 5px;margin-left: -7px;cursor:pointer;" onclick="order(\'desc\',\'' + table[i].headerNameEN + '\');">' + 
			  "</div>").appendTo($tr);
			} else if (table[i].checkboxHead) {
				$("<th>").html('<input id="' + table[i].headerNameEN + '" name="' + table[i].headerNameEN + '" type="checkbox" value="1" checked onMouseOver="showTip('+ i +')">' + table[i].headerNameCN).appendTo($tr);
			} else if (table[i].checkboxHeadTime) {
				$("<th>").html('<input id="' + table[i+1].headerNameEN + '" name="' + table[i+1].headerNameEN + '" type="checkbox" value="1" checked  onMouseOver="showTip('+ (i+1) +')">' + table[i].headerNameCN).appendTo($tr);
			} else if (table[i].other){
				$("<th>").html(table[i].headerNameCN + table[i].otherBody).appendTo($tr);
			} else {
				if(table[i].headerNameEN == "operation"){
					$("<th>").html(table[i].headerNameCN).appendTo($tr).css(table[i].tableStyle || '').css({width: "15%"});
				} else if (table[i].headerNameEN == "hide"){
					$('<th class="hideTable" hidden="hidden">').html(table[i].headerNameCN).appendTo($tr);
				} else if (table[i].headerNameEN == "showHide"){
					$('<th onclick="showHideTable()" width="5px">').html("").appendTo($tr);
				} else {
					$("<th>").html(table[i].headerNameCN).appendTo($tr).css(table[i].tableStyle || '');
				}
				
			}
		}
	}
	if (callbackSearch && typeof callbackSearch === 'function') {
		var total = document.getElementById("total");
		if (total) {
			total.innerText = '共0页  / 共0条记录 ';
		}
		if ($(".turnPage") && $(".turnPage").html()) {
			$(".turnPage").resetTurnPage();
		} else {
			$(".turnPage").createTurnPage({ backFn: callbackSearch });
		}
	}
}

function createTableBody(tableBodyID, table, data, alertMessge, turnPage) {
	if (!$("#page").val()) {
		$("#page").val(1);
	}
	clearTable(tableBodyID);
	$("#chkAll").attr("checked", false);
	if (!turnPage) {
		if (lastTotalCnt != totalCnt || lastTotalPage != totalPage){
			var total = document.getElementById("total");
			if (total) {
				total.innerText = '共' + totalPage + '页 / 共' + totalCnt + '条记录 ';
			}
			lastTotalPage = totalPage;
		}
		if (lastTotalCnt != totalCnt) {
			$(".turnPage").resetTurnPage();
			lastTotalCnt = totalCnt;
		}
	}
	// 当前页数
	var currentPage = parseInt($('#currentPage').val(), 10) || 1;
	// 每页显示的条数
	var rows = parseInt($('#rows').val(), 10);
	// 查询数据的数组长度
	var length = data && data.length || 0;
	// 画面表格的body
	var tbody = $("#" + tableBodyID);
	if (length == 0 && !alertMessge) {
		showMessge(messageContent["Search.NoResultFound"]);
		$('#currentPage').val(1);
		$("#page").val(1);
	} else {
		var tableLength = table.length;
		var $tr = undefined;
		var rowNo = 1;
		for(var i=0; i<length; i++){
			// 序号
			rowNo = (currentPage - 1) * rows + i + 1 || i + 1;
			$tr = $('<tr>').appendTo(tbody);
			for (var j=0; j<tableLength; j++) {
				if (table[j].tableDisplay) {
					var tdHtml = "";
					var tdValue= "";
					var value = data[i][table[j].headerNameEN];
					if (table[j].type == "list") {
						if(typeof value === 'boolean') {
							if (value === true) {
								tdValue = table[j].value && table[j].value[1];
								table[j].tableStyle = table[j].styleList && table[j].styleList[1] || {};
							} else if (value === false) {
								tdValue = table[j].value && table[j].value[0];
								table[j].tableStyle = table[j].styleList && table[j].styleList[0] || {};
							}
			            } else if (table[j].type == "date") {
							tdValue = table[j].value.replace(/,/g, "\r\n") && table[j].value[value];
						} else {
			            	tdValue = table[j].value && table[j].value[value];
			            	table[j].tableStyle = table[j].styleList && table[j].styleList[value] || {};
			            }
					} else if (table[j].type == "date") {
						tdValue = date2String(value) || '-';
					} else if (table[j].type == "dateTime") {
						tdValue = timeStamp2String(value) || '-';
					} else if (table[j].type == "time") {
						tdValue = formatTime(value) || '-';
					} else if (table[j].type == "toFixed") {
						tdValue = value && Number(value).toFixed(table[j].fixedLength) || '0';
					} else if (table[j].type== "tableSelect") {
						if(table[j].tableListValue){
							for (var k=0; k<table[j].tableListValue.length; k++) {
								if (table[j].tableListValue[k] == value) {
									tdValue =  table[j].ListValue[k] == undefined ? '-' : table[j].ListValue[k];
									break;
								}
							}
						}
					} else {
						if (table[j].headerNameEN == "checkbox") {
							tdValue = '<input name="chk" id="chk" type="checkbox">';
						} else if (table[j].headerNameEN == "number") {
							tdValue = rowNo;
						} else if (table[j].headerNameEN == "updatePwd") {
							tdValue = '<a class="details" id=' + (table.headerNameEN || '') + ' href="#" onclick="chkBefore('+ i +',\'updatePwd\');">修改</a>';
						} else if (table[j].headerNameEN == "reviewState") {
							if (data[i].reviewState == 0) {
								tdValue = '<span onclick="reviewState('+ i +')" id="reviewState'+ i +'" class="bacLightGreen details operationWord" style="color: white;">确认</span>'
							} else if (data[i].reviewState == 2) {
								tdValue = '<span id="reviewState'+ i +'" class="details operationWord">已确认</span>'
							}
							
						} else if (table[j].headerNameEN == "operation") {
							var tableClickMethod = table[j].tableClickMethod || "details";
							var tableOperationName = table[j].tableOperationName || "操作";
							if (table[j].image) {
								tableOperationName = table[j].image;
							}
							var tableUpdate = "";
							var tableDel = "";
							var tableDownload = "";
							 if(table[j].tabUpdate){
								 tableUpdate = 
						         '<span onclick="chkBefore('+ i +',\'update\')"' + 
						            'class="bacHoverBlue details operationWord">修改</span>'
					       	 }
							 if(table[j].tabDel){
								 tableDel = 
						         '<span onclick="chkBefore('+ i +',\'delete\')"' +
						            'class="bacHoverRed details operationWord">删除</span>'
					       	 }
							 if (table[j].download){
								 tableDownload = '<img style="width:30px;height:25px;" src = "'+ (table[j].src || "") +'" onclick = "'+ (table[j].tableClickMethod || "") +'(\''+ i +'\')"/>'
							 }
							 if (table[j].tabDetalis){
								tdValue = '<div id="' + tableClickMethod + i + '">'+
						         '<span onclick="' + tableClickMethod + '(' + i + ')"' +
						       		'class="bacHoverGreen details operationWord">'+ tableOperationName +'</span>' +
						       		tableUpdate + tableDel +'</div>';
							 } else {
								 tdValue = '<div id="' + tableClickMethod + i + '">' + tableUpdate + tableDel + tableDownload +'</div>';
							 }
						
						} else {
							tdValue = value == undefined ? '-' : value;
						}
						if (table[j].value && table[j].styleList) {
							table[j].tableStyle = table[j].styleList[table[j].value[tdValue]] || {};
						}
					}
					if (table[j].tagName == "select") {
						tdHtml = '<select class="form-control" style="height:30px;padding:0;" id="' + (table[j].headerNameEN + i || '') + '" name="' + name + '"';
						if (table[j].tableChangeMethod) {
							tdHtml = tdHtml + ' onchange="' + table[j].tableChangeMethod + '(' + i + ')"';
						}
						if (table[j].disabled) {
							tdHtml = tdHtml + ' disabled="disabled"';
						}
						tdHtml = tdHtml + '><option value="">请选择</option>';
						if (table.type == "list") {
							var valueLength = table.value && table.value.length || 0;
							for (var k=0; k<valueLength; k++) {
								tdHtml = tdHtml + '<option value="' + tdValue[k] + '">' + (table.value[k]) + '</option>';
							}
						} else {
							if (tdValue != "-") {
								var listLength = tdValue && tdValue.length;
								for (var k=0; k<listLength; k++) {
									tdHtml = tdHtml + '<option value="' + tdValue[k] + '">' + tdValue[k] + '</option>';
								}
							}
						}
						tdHtml = tdHtml + '</select>';
					} else if (table[j].tableTagName == "input") {
						tdHtml = '<input id="' + (table[j].headerNameEN + i || '') + '" style="margin: 0;float: center;" value="' + tdValue + '">';
					} else if (table[j].tableTagName == "a") {
						tdHtml = '<a id="' + (table[j].headerNameEN + i || '') + '" onclick="' + table[j].tableClickMethod + '(' + i + ')" style="cursor:pointer;text-align: left;">' + tdValue + '</a>';
					} else if (table[j].tagName == "p" || table[j].tableTagName == "p") {
						tdHtml = '<p id="' + (table[j].headerNameEN + i || '') + '" style="margin:0">' + tdValue + '</p>';
					} else {
						tdHtml = tdValue;
					}
					$("<td>").html(tdHtml).appendTo($tr).css(table[j].tableStyle || '');
				}
			}
		}
	}
}

function detailHeadContent(table) {
	return $("<th>").html(table.headerNameCN || '');
}

function createDetailHead(detailHeadID, table, detailType, hidden) {
	var thead = $("#" + detailHeadID);
	if (thead && thead.length > 0) {
		thead.html('');
		var $tr = $('<tr>').appendTo(thead);
		var length = table.length;
		for(var i=0; i<length; i++){
			if (table[i].detailDisplay && table[i].detailType && table[i].detailType == detailType) {
				if (!hidden || !table[i].hidden) {
					detailHeadContent(table[i]).appendTo($tr).css(table[i].detailStyle || '');
				}
			}
		}
	}
}
function detailBodyContent(table, data) {
	var tdHtml = "";
	var tdValue= "";
	var value = "";
	var name = (table.headerNameEN && (table.headerNameEN.substr(0, 1).toUpperCase() + table.headerNameEN.substr(1))) || '';
	if (data) {
		value = data[table.headerNameEN];
		if (table.type == "date") {
			tdValue = date2String(value) || '-';
		} else if (table.type == "dateTime") {
			tdValue = timeStamp2String(value) || '-';
//		} else if (table.type == "time") {
//			tdValue = formatTime(value) || '-';
		} else if (table.type == "list") {
			if(typeof value === 'boolean') {
				if (value === true) {
					tdValue = table.value && table.value[1] || '-';
				} else if (value === false) {
					tdValue = table.value && table.value[0] || '-';
				} else {
					tdValue = "-";
				}
            } else {
            	tdValue = table.value && table.value[tdValue] || '';
            }
		} else {
			tdValue = value == undefined ? '-' :  value;
		}
	}
	if (table.tagName == "input") {
		tdHtml = '<input maxlength=' + table.maxlength + ' type="text" class="form-control" id=' + (table.headerNameEN || '') + ' name=' + name + ' value="' + tdValue + '">';
	} else if (table.tagName == "select") {
		if (table.tableChangeMethod) {
			tdHtml = '<select class="form-control" id="' + (table.headerNameEN || '') + '" name="' + name + '" onchange="' + table.tableChangeMethod + '()"><option value="">请选择</option>';
		} else {
			tdHtml = '<select class="form-control" id="' + (table.headerNameEN || '') + '" name="' + name + '"><option value="">请选择</option>';
		}
		if (table.type == "list") {
			var valueLength = table.value && table.value.length || 0;
			for (var i=0; i<valueLength; i++) {
				if (table.selectValue && table.selectValue.length > 0) {
					tdHtml = tdHtml + '<option value="' + table.selectValue[i] + '">' + (table.value[i]) + '</option>';
				} else {
					tdHtml = tdHtml + '<option value="' + i + '">' + (table.value[i]) + '</option>';
				}
			}
		}
		tdHtml = tdHtml + '</select>';
	} else if (table.tagName == "a") {
		tdHtml = '<a id=' + (table.headerNameEN || '') + ' href="#" onclick="' + (table.clickMethod || '') + ';return false;"' + (table.detailOperationName || tdValue) + '</a>'
	} else if (table.tagName == "date") {
		var id = table.headerNameEN && (table.headerNameEN.replace("DTTM", "Date")) || '';
		tdHtml = '<div id="' + id + '1" class="input-group date" data-date-format="' + (table.dateFormat || 'yyyy-mm-dd') + '">' + 
            	 '<input id="' + id + '" name="' + (name && name.replace("DTTM", "Date")) + '" class="form-control" type="text" value="' + tdValue + '">' + 
            	 '<span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span>' +
            	 '<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span></div>'
	} else if (table.tagName == "map") {
		tdHtml = '<div id="tableContainer" style="height:35px;" onclick="' + (table.clickMethod || '') + '"></div>';
	} else if (table.tagName == "p") {
		tdHtml = '<p id="' + (table.headerNameEN || '') + '" style="margin:0">' + tdValue + '</p>';
	} else if (table.tagName == "button") {
		tdHtml = '<div id="'+ table.headerNameEN + '"><button type="button" class="btn btn-primary"' + 'onclick="' + (table.clickMethod || '') + '>' + (table.buttonName || '按钮') + '</button></div>';
	} else if (table.tagName == "span"){
		tdHtml = '<span id=' + (table.headerNameEN || '') + '>'+ tdValue +'</span>';
	} else if (table.tagName == "spanSelect"){
		var tdValueNum, color;
		if(tdValue == true){
			tdValueNum = 1;
		}else if(tdValue == false){
			tdValueNum = 0;
		}else{
			tdValueNum = tdValue;
		}
		if (table.color) {
			color = 'style="' + table.color[tdValueNum] + ';"'
		} else {
			color = "";
		}
		tdHtml = '<span id="' + (table.headerNameEN || '') + '" ' + color + '>'+ table.value[tdValueNum] +'</span>';
	} else if (table.tagName == "password") {
		tdHtml = '<input maxlength=' + table.maxlength + ' type="password" class="form-control" id=' + (table.headerNameEN || '') + ' name=' + name + ' value="' + tdValue + '">';
	}
	 return $("<td>").html(tdHtml);
}
function createDetailBody(detailBodyID, table, data, detailType, hidden) {
	var tbody = $("#" + detailBodyID);
	if (tbody && tbody.length > 0) {
		tbody.html('');
		var $tr = $('<tr>').appendTo(tbody);
		var tableLength = table.length;
		for (var i=0; i<tableLength; i++) {
			if (table[i].detailDisplay && table[i].detailType && table[i].detailType == detailType) {
				if (!hidden || !table[i].hidden) {
					detailBodyContent(table[i], data).appendTo($tr).css(table[i].detailStyle || '');
				}
			}
		}
	}
}
function createComBody(detailBodyID, table, data, detailType, hidden) {
	var bodyID = $("#" + detailBodyID);
	if (bodyID && bodyID.length > 0) {
		bodyID.html('');
		var length = table.length;
		for(var i=0; i<length; i++){
			if (table[i].detailDisplay && table[i].detailType && table[i].detailType == detailType) {
				if (!hidden || !table[i].hidden) {
					detailComBodyContent(table[i], data).appendTo(bodyID).css(table[i].detailStyle || '');
				}
			}
		}
	}
}
function detailComBodyContent(table, data) {
	var tdHtml = "";
	var tdValue= "";
	var value = "";
	var divHtml = "";
	var name = (table.headerNameEN && (table.headerNameEN.substr(0, 1).toUpperCase() + table.headerNameEN.substr(1))) || '';
	if (data) {
		value = data[table.headerNameEN];
		if (table.type == "date") {
			tdValue = date2String(value) || '-';
		} else if (table.type == "dateTime") {
			tdValue = timeStamp2String(value) || '-';
//		} else if (table.type == "time") {
//			tdValue = formatTime(value) || '-';
		} else if (table.type == "list") {
			if(typeof value === 'boolean') {
				if (value === true) {
					tdValue = table.value && table.value[1] || '-';
				} else if (value === false) {
					tdValue = table.value && table.value[0] || '-';
				} else {
					tdValue = "-";
				}
            } else {
            	tdValue = table.value && table.value[tdValue] || '';
            }
		} else {
			tdValue = value == undefined ? '-' :  value;
		}
	}
	if (table.tagName == "input") {
		tdHtml = 
				'<input maxlength=' + table.maxlength + ' type="text" class="form-control" id=' + (table.headerNameEN || '') + ' name=' + name + ' value="' + tdValue + '">' +
				'</div>';
	} else if (table.tagName == "select") {
		tdHtml = '<select class="form-control" onchange="' + (table.onChange || '') + '" id="' + (table.headerNameEN || '') + '" name="' + name + '"><option value="">请选择</option>';
		if (table.type == "list") {
			var valueLength = table.value && table.value.length || 0;
			for (var i=0; i<valueLength; i++) {
				if (table.selectValue && table.selectValue.length > 0) {
					tdHtml = tdHtml + '<option value="' + table.selectValue[i] + '">' + (table.value[i]) + '</option>';
				} else {
					tdHtml = tdHtml + '<option value="' + i + '">' + (table.value[i]) + '</option>';
				}
			}
		}
		tdHtml = tdHtml + '</select>';
	} else if (table.tagName == "a") {
		tdHtml = '<a id=' + (table.headerNameEN || '') + ' href="#" onclick="' + (table.clickMethod || '') + ';return false;"' + (table.detailOperationName || tdValue) + '</a>'
	} else if (table.tagName == "date") {
		var id = table.headerNameEN && (table.headerNameEN.replace("DTTM", "Date")) || '';
		tdHtml = '<div id="' + id + '1" class="input-group date" data-date-format="' + (table.dateFormat || 'yyyy-mm-dd') + '">' + 
            	 '<input id="' + id + '" name="' + (name && name.replace("DTTM", "Date")) + '" class="form-control" type="text" value="' + tdValue + '">' + 
            	 '<span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span>' +
            	 '<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span></div>'
	} else if (table.tagName == "map") {
		tdHtml = '<div id="tableContainer" style="height:200px;width:200%;" onclick="' + (table.clickMethod || '') + '"></div>';
	} else if (table.tagName == "p") {
		tdHtml = '<p id="' + (table.headerNameEN || '') + '" style="margin:0">' + tdValue + '</p>';
	} else if (table.tagName == "button") {
		tdHtml = '<div id="'+ table.headerNameEN + '"><button type="button" class="btn btn-primary"' + 'onclick="' + (table.clickMethod || '') + '>' + (table.buttonName || '按钮') + '</button></div>';
	} else if (table.tagName == "span"){
		tdHtml = '<span id=' + (table.headerNameEN || '') + '>'+ tdValue +'</span>';
	} else if (table.tagName == "spanSelect") {
		var tdValueNum, color;
		if (tdValue == true){
			tdValueNum = 1;
		} else if(tdValue == false) {
			tdValueNum = 0;
		} else{
			tdValueNum = liValue;
		}
		if (table.color) {
			color = 'style="' + table.color[tdValueNum] + ';"'
		} else {
			color = "";
		}
		tdHtml = '<span id="' + (table.headerNameEN || '') + '" ' + color + '>'+ table.value[tdValueNum] +'</span>';
	} else if (table.tagName == "password") {
		tdHtml = '<input maxlength=' + table.maxlength + ' type="password" class="form-control" id=' + (table.headerNameEN || '') + ' name=' + name + ' value="' + tdValue + '">';
	}
	if (table.triplet) {
		divHtml = '<label for=' + (table.headerNameEN || '') + ' class="col-sm-3 control-label partConditionTitle marginBottom2Ten">'+ 
		(table.headerNameCN || '') +'</label>' + 
		'<div class="col-sm-8 partCondition">'+ tdHtml + '</div>';
		 return $('<div class="col-sm-4 marginBottom2Ten">').append(divHtml);
	} else if (table.duplicate) {
		divHtml = '<label for=' + (table.headerNameEN || '') + ' class="col-sm-2 control-label partConditionTitle marginBottom2Ten">'+ 
		(table.headerNameCN || '') +'</label>' + 
		'<div class="col-sm-3 partCondition">'+ tdHtml + '</div>';
		 return $('<div class="col-sm-8 marginBottom2Ten">').append(divHtml);
	} else if (table.quarter) {
		divHtml = '<label for=' + (table.headerNameEN || '') + ' class="col-sm-4 control-label partConditionTitle marginBottom2Ten">'+ 
		(table.headerNameCN || '') +'</label>' + 
		'<div class="col-sm-8">'+ tdHtml + '</div>';
		 return $('<div class="col-sm-3 marginBottom2Ten">').append(divHtml);
	} else {
		divHtml = '<label for=' + (table.headerNameEN || '') + ' class="col-sm-1 control-label partConditionTitle marginBottom2Ten">'+ 
		(table.headerNameCN || '') +'</label>' + 
		'<div class="col-sm-2 partCondition">'+ tdHtml + '</div>';
		 return $('<div class="col-sm-12 marginBottom2Ten">').append(divHtml);
	}
	
	
}
function createDetailUlBody(detailUlBodyID, li, data, detailType, hidden) {
	var UlDiv = $("#" + detailUlBodyID);
	if (UlDiv) {
		UlDiv.html('');
		var $ul = $('<ul>').appendTo(UlDiv);
		var liLength = li.length;
		for (var i=0; i<liLength; i++) {
			if (li[i].detailDisplay && li[i].detailType && li[i].detailType == detailType) {
				if (!hidden || !li[i].hidden) {
					detailUlBodyContent(li[i], data).appendTo($ul).css(li[i].detailStyle || '');
				}
			}
		}
	}
}
function detailUlBodyContent(table, data) {
	var liHtml = "";
	var liValue= "";
	var value = "";
	var name = (table.headerNameEN && (table.headerNameEN.substr(0, 1).toUpperCase() + table.headerNameEN.substr(1))) || '';
	if (data) {
		value = data[table.headerNameEN];
		if (table.type == "date") {
			liValue = date2String(value) || '-';
		} else if (table.type == "dateTime") {
			liValue = timeStamp2String(value) || '-';
		} else if (table.type == "time") {
			liValue = formatTime(value) || '-';
		} else if (table.type == "list") {
			if(typeof value === 'boolean') {
				if (value === true) {
					liValue = table.value && table.value[1] || '-';
				} else if (value === false) {
					liValue = table.value && table.value[0] || '-';
				} else {
					liValue = "-";
				}
            } else {
            	liValue = table.value && table.value[liValue] || '';
            }
		} else {
			liValue = value == undefined ? '-' :  value;
		}
	}
	if (table.tagName == "input") {
		liHtml = '<input maxlength=' + table.maxlength + ' type="text" class="form-control" id=' + (table.headerNameEN || '') + ' name=' + name + ' value="' + liValue + '">';
	} else if (table.tagName == "select") {
		liHtml = '<select class="form-control" id="' + (table.headerNameEN || '') + '" name="' + name + '"><option value="">请选择</option>';
		if (table.type == "list") {
			var valueLength = table.value && table.value.length || 0;
			for (var i=0; i<valueLength; i++) {
				if (table.selectValue && table.selectValue.length > 0) {
					liHtml = liHtml + '<option value="' + table.selectValue[i] + '">' + (table.value[i]) + '</option>';
				} else {
					liHtml = liHtml + '<option value="' + i + '">' + (table.value[i]) + '</option>';
				}
			}
		}
		liHtml = liHtml + '</select>';
	} else if (table.tagName == "a") {
		liHtml = '<span class="grayWord">' + table.headerNameCN +': </span><a id=' + (table.headerNameEN || '') + ' href="#" onclick="' + (table.clickMethod || '') + ';return false;"' + (table.detailOperationName || liValue) + '</a>'
	} else if (table.tagName == "aSpan") {
		liHtml = '<span class="grayWord">' + table.headerNameCN + ': </span><a id=' + (table.headerNameEN || '') + ' href="#" onclick="' + (table.clickMethod || '') + ';return false;"' + (table.detailOperationName || liValue) + '</a>'
	} else if (table.tagName == "date") {
		var id = table.headerNameEN && (table.headerNameEN.replace("DTTM", "Date")) || '';
		liHtml = '<div id="' + id + '" class="input-group date" data-date-format="' + (table.dateFormat || 'yyyy-mm-dd') + '">' + 
            	 '<input id="' + id + '" name="' + (name && name.replace("DTTM", "Date")) + '" class="form-control" type="text" value="' + liValue + '">' + 
            	 '<span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span>' +
            	 '<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span></div>'
	} else if (table.tagName == "map") {
		liHtml = '<div id="tableContainer" style="'+ table.mapStyle +'" onclick="' + (table.clickMethod || '') + '"></div>';
	} else if (table.tagName == "p") {
		liHtml = '<p id="' + (table.headerNameEN || '') + '" style="margin:0">' + liValue + '</p>';
	} else if (table.tagName == "button") {
		liHtml = '<div id="'+ table.headerNameEN + '"><button type="button" class="btn btn-primary"' + 'onclick="' + (table.clickMethod || '') + '>' + (table.buttonName || '按钮') + '</button></div>';
	} else if (table.tagName == "span"){
		liHtml = '<span class="grayWord">' + table.headerNameCN + ': ' + '</span><span id=' + (table.headerNameEN || '') + '>' + liValue + '</span>';
	} else if (table.tagName == "spanOnly"){
		liHtml = '<span id=' + (table.headerNameEN || '') + '>'+ liValue +'</span>';
	} else if (table.tagName == "spanSelect"){
		var liValueNum, color;
		if(liValue == true){
			liValueNum = 1;
		}else if(liValue == false){
			liValueNum = 0;
		}else{
			liValueNum = liValue;
		}
		if (table.color) {
			color = 'style="color:' + table.color[liValueNum] + ';"'
		} else {
			color = "";
		}
		liHtml = '<span class="grayWord">' + table.headerNameCN + ': ' + '</span><span id=' + (table.headerNameEN || '')  + '" ' + color +  '>' + table.value[liValueNum] + '</span>';
	} else if (table.tagName == "meter"){
		liHtml = '<div id=' + (table.headerNameEN || '') + ' style="'+ table.detailStyleAll +'"></div>';
	}
	if(table.setLi){
		return $("<li style='"+ table.liStyle +"'>").append(liHtml);
	}else{
		return $("<li>").append(liHtml);
	}
	
}
function createDetailAll(detailTableID, table, data, detailType, displayColumn, hidden) {
	displayColumn = displayColumn && displayColumn > 0 ? displayColumn : 3;
	var detailTable = $("#" + detailTableID);
	if (detailTable && detailTable.length > 0){
		detailTable.html('');
		var length = table.length;
		var $tr = undefined;
		var k = 0;
		for(var i=0; i<length; i++){
			if (table[i].detailDisplay && table[i].detailType && table[i].detailType == detailType) {
				if (k % displayColumn == 0) {
					$tr = $('<tr>').appendTo(detailTable);
				}
				detailHeadContent(table[i]).appendTo($tr).css(table[i].detailStyle || '');
//				detailBodyContent(table[i], data || "-").appendTo($tr).css(table[i].detailBodyStyle || '');
				detailBodyContent(table[i], data).appendTo($tr).css(table[i].detailBodyStyle || '');
				k++;
			}
		}
	}
}

function checkForm(formID, table) {
	var tableLength = table && table.length || 1;
	var message = undefined;
	$("#" + formID + " :input").each(function(i, item) {
		if (item.id && (item.value == undefined || item.value == "")) {
			message = "画面项目" + (item.name || item.id);
			for (var j=0; j<tableLength; j++) {
				var t = table && table[j];
				if (t) {
					var headerNameEN = t.headerNameEN;
					var itemID = item.id;
					if (t.tagName == "date" && itemID && (itemID.substr(itemID.length - 4) == "Date")) {
						itemID = itemID.replace("Date", "DTTM");
					}
					if (headerNameEN == itemID && !t.allowEmpty) {
						if (t.emptyMessage) {
							message = t.emptyMessage;
						} else {
							message = t.headerNameCN;
						}
						return false;
					} else {
						if (headerNameEN == itemID) {
//							if (t.type == "list") {
//								$("#" + itemID).val(0);
//							}
							message = undefined;
							break;
						}
					}
				}
			}
		}
	})
	if (message) {
		showMessge(message + "不能为空！");
		return false;
	} else {
		return true;
	}
}

function setFormDisabled(formID) {
	$("#" + formID + " :input").each(function(i, item) {
		item.disabled = true;
	})
}
function turnPage(data){
	var currentData = [];
	totalCnt = data && data.length || 0;
	totalPage = 0;
	if (totalCnt > 0) {
		var rows = parseInt($("#rows").val(), 10);
		var currentPage = parseInt($("#currentPage").val()) || 1;
		if (totalCnt % rows > 0) {
			totalPage = parseInt(totalCnt / rows, 10) + 1;
		} else {
			totalPage = parseInt(totalCnt / rows, 10);
		}
		var start = (currentPage - 1) * rows;
		var end = currentPage * rows > totalCnt ? totalCnt : currentPage * rows;
		currentData = data.slice(start, end);
	}
	return currentData;
}
function formatFileSize(size){
	if (!isNaN(parseInt(size, 10))) {
		i = Math.floor(Math.log(size) / Math.log(1024));
	    sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
	    return (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
	}
}
function addTitle(title){
	$('#title').html('');
	var $title = $('#title');
	var strong = document.createElement("strong");
	strong.innerHTML = titleContent[title];
	$title.append(strong);
}
function order(orderType, headerNameEN){
	if($('#' + headerNameEN + "Order").val()){
		if(orderType == "asc" || $('#' + headerNameEN + "Order").val() == 0){
			$('#' + headerNameEN + "Order").val(1);
			$('#' + headerNameEN + "Order1").show();
			$('#' + headerNameEN + "Order0").hide();
		}else if(orderType == "desc" || $('#' + headerNameEN + "Order").val() == 1){
			$('#' + headerNameEN + "Order").val(0);
			$('#' + headerNameEN + "Order1").hide();
			$('#' + headerNameEN + "Order0").show();
		}
	} else{
		$('#' + headerNameEN + "Order").val(0);
		$('#' + headerNameEN + "Order1").hide();
		$('#' + headerNameEN + "Order0").show();
	}
	$('#' + headerNameEN + "Order0").css({
		'margin-top' : '0px',
    	'margin-left' : '0px',
	});
	$('#' + headerNameEN + "Order1").css({
		'margin-top' : '0px',
    	'margin-left' : '0px',
	});
	search(headerNameEN);
}
function clearOrder(lastheaderNameEN){
	if(lastheaderNameEN){
		$("#"+ lastheaderNameEN + "Order").val("");
		$("#"+ lastheaderNameEN + "Order0").show();
		$("#"+ lastheaderNameEN + "Order1").show();
		$("#"+ lastheaderNameEN + "Order0").css({
			'margin-top' : '-10px',
	    	'margin-left' : '0px',
		});
		$("#"+ lastheaderNameEN + "Order1").css({
			'margin-top' : '5px',
	    	'margin-left' : '-7px',
		});
	}
}
function changeMonth(index){
	var nowDate;
	if(flagDate){
		nowDate = flagDate;
	}else {
		nowDate = getSystemTime();
	}
	nowDate = new Date(nowDate.getFullYear(), nowDate.getMonth() + index, nowDate.getDate());
	month = date2String(nowDate);
	flagDate = nowDate;
	$("#showMonth").html(nowDate.getFullYear() + "年" + (nowDate.getMonth()+1) + "月");
	getDayCount(month);
}
function getDayCount(month){
	$("#dayList").empty();
	var nowDate = stringToDate(month);
	var maxDay = new Date(nowDate.getFullYear(), nowDate.getMonth()+1, 0).getDate();
	var firstDay = new Date(nowDate.getFullYear(), nowDate.getMonth(), 1).getDay();
    var $ul = $("#dayList");
    var $li = $('<ul style="margin-bottom: 3px">').appendTo($ul);
    var a = new Array("日", "一", "二", "三", "四", "五", "六");
    $('<li class="dayLi" style="padding-top: 15px"><span class="glyphicon glyphicon-chevron-left" onclick="changeMonth(-1)" aria-hidden="true"><span></li>').appendTo($li);
    for(var i=1; i<=maxDay; i++){
    	$('<li id="li'+ i +'" class="dayLi" onclick="showDay('+ i +',\''+ month +'\')">'+ '<span>'+ a[(firstDay+i-1)%7] +'</span><br><span>' + i +'</span></li>').appendTo($li);
    }
    $('<li class="dayLi" style="padding-top: 15px"><span class="glyphicon glyphicon-chevron-right" onclick="changeMonth(1)" aria-hidden="true"><span></li>').appendTo($li);
    $("#dayList").append('<a onclick="showForm()">高级</a>');
    showDay(nowDate.getDate(), month);
}
function showForm(){
	if(document.getElementById("hideform").hidden){
		$("#hideform").attr("hidden", false);
	} else{
		$("#hideform").attr("hidden", true);
	}
}
function changeYear(index, startMonth){
	var balanceStartMonth = startMonth;
	var nowDate;
	if(flagDate){
		nowDate = flagDate;
	}else {
		nowDate = getSystemTime();
	}
	nowDate = new Date(nowDate.getFullYear() + index, nowDate.getMonth(), nowDate.getDate());
	flagDate = nowDate;
	$("#showYear").html(nowDate.getFullYear() + "年");
	$("#monthList").empty();
	var thisYear = nowDate.getFullYear() == getSystemTime().getFullYear();
	var startYear = balanceStartMonth.substring(0,4) == nowDate.getFullYear();
	var startMonth = balanceStartMonth.substring(4,6);
	var $ul = $("#monthList");
	var $li = $('<ul style="margin-bottom: 3px">').appendTo($ul);
	if(startYear){
		$('<li class="monthLiUnclick"><span class="glyphicon glyphicon-chevron-left" aria-hidden="true"><span></li>').appendTo($li);
	} else {
		$('<li class="monthLi" onclick="changeYear(-1, \'' + balanceStartMonth + '\')"><span class="glyphicon glyphicon-chevron-left" aria-hidden="true"><span></li>').appendTo($li);
	}
	for(var i=1; i<=12; i++){
		if(thisYear && (getSystemTime().getMonth() + 1) < i){
			$('<li id="li'+ i +'" class="monthLiUnclick"><span style="font-size:18px;color:#DADADA">' + i + '<span style="font-size:14px;color:#DADADA">月<span>' + '</span></li>').appendTo($li);
		} else if(startYear && startMonth > i){
			$('<li id="li'+ i +'" class="monthLiUnclick"><span style="font-size:18px;color:#DADADA">' + i + '<span style="font-size:14px;color:#DADADA">月<span>' + '</span></li>').appendTo($li);
		} else{
			$('<li id="li'+ i +'" class="monthLi" onclick="showMonth('+ i +')"><span style="font-size:18px;">' + i +'<span style="font-size:14px;">月<span>' + '</span><p style="font-weight:bold;font-size:18px" class="showBottom" id="p'+i+'" hidden>——</p></li>').appendTo($li);
		}
	}
	if(thisYear){
		$('<li class="monthLiUnclick"><span class="glyphicon glyphicon-chevron-right" aria-hidden="true"><span></li>').appendTo($li);
	} else {
		$('<li class="monthLi" onclick="changeYear(1, \'' + balanceStartMonth + '\')"><span class="glyphicon glyphicon-chevron-right" aria-hidden="true"><span></li>').appendTo($li);
	}
}
function checkNum(ID, type){
	var value = $("#" + ID).val();
	if(type == 1){
		if(!/^[0-9]*$/.test(value)){
			$("#" + ID).focus();
			$("#" + ID).tips({
				side : 1,
				msg : "请输入有效数字!",
				bg : '#AE81FF',
				time : 3
			});
			return false;
	    }
	} else if(type == 2){
		if(!/^0+(\.\d*)?$/.test(value)){
			$("#" + ID).focus();
			$("#" + ID).tips({
				side : 1,
				msg : "请输入0-1之间有效小数!",
				bg : '#AE81FF',
				time : 3
			});
			return false;
		}
	} else if(type == 3){
		if($("#" + ID).val() == ""){
			$("#" + ID).focus();
			$("#" + ID).tips({
				side : 1,
				msg : "不能为空!",
				bg : '#AE81FF',
				time : 3
			});
			return false;
		}
	} else {
		if(!/^[+-]?\d+(\.\d*)?$/.test(value)){
			$("#" + ID).focus();
			$("#" + ID).tips({
				side : 1,
				msg : "请输入有效小数!",
				bg : '#AE81FF',
				time : 3
			});
			return false;
		}
	}
	return true;
}
function getSystemTime(){
	if ($('#systemTime', parent.document).val()) {
		return new Date(parseInt($('#systemTime', parent.document).val(), 10));
	} else {
		return new Date();
	}
}
/*table悬浮*/
function scrollTableSuspend(scrollBody, tableID, tableID1, theadID, divID, minusHeight, heightTableHeight, heightFlag, specialID, specialHeight) {
	if (heightTableHeight != '' && heightTableHeight && minusHeight && minusHeight != '') {
		var partTableHeight = $("body").height() - $("#" + heightTableHeight).offset().top - parseInt(minusHeight);
	}
	$("." + scrollBody).scroll(function(){ 
		if (heightTableHeight != '' && heightTableHeight && minusHeight && minusHeight != '') {
			if ($("." + scrollBody).scrollTop() > 0 && $("." + scrollBody).scrollTop() < $("#"+ tableID).height() - partTableHeight + parseInt(minusHeight)) {
				var partTable;
				if (heightFlag && specialID && specialHeight && $("#" + specialID).height() < specialHeight) {
					partTable = $("body").height() - $("#" + heightTableHeight).offset().top - 3 * parseInt(minusHeight);
					$("#" + heightTableHeight)[0].style.marginBottom = '150px';
				} else {
					partTable = partTableHeight + $("." + scrollBody).scrollTop(); 
					$("#" + heightTableHeight)[0].style.marginBottom = '100px';
				}
				$("#" + heightTableHeight)[0].style.height = partTable + "px";
			} else if (heightFlag && minusHeight && minusHeight != '' && 
				$("." + scrollBody).scrollTop() < partTableHeight + $("#"+ tableID).height() - $("body").height() + 3 * parseInt(minusHeight)) {
				var partTable = $("." + scrollBody).scrollTop() + partTableHeight - $("body").height();
				$("#" + heightTableHeight)[0].style.height = partTable + "px";
			}
		}
		if ($("." + scrollBody).scrollTop() < $("#" + tableID).offset().top - $("#" + divID).offset().top) {
			$("#" + tableID1).hide();
		} else {
			if ($("#" + tableID).offset().top &&  $("#" + divID).offset().top) {
			var theadWidth = $("#" + theadID).width();
			var theadTop = $("." + scrollBody).scrollTop() - ($("#" + tableID).offset().top - $("#" + divID).offset().top);
			$("#" + tableID1).css({'width' : theadWidth,'top' : theadTop});
			$("#" + tableID1).html($("#" + theadID)[0].outerHTML);
			var length = $("#" + theadID)[0].children[0].children.length;
			for (var i=0; i<length; i++) {
				$("#" + tableID1)[0].children[0].children[0].children[i].style.width
				= $("#" + theadID)[0].children[0].children[i].clientWidth + "px";
			}
			$("#" + tableID1).show();
			} else {
				$("#" + tableID1).hide();
			}
		}
	})
}
//删除
function del(){
	var checkbox = getCheckbox("chk");
	if (checkbox.count == 0) {
		showMessge(messageContent["Select.NotFound"]);
	} else {
		showMessge(messageContent["Delete.Confirm"], "model2");
		saveFlag = "delete";
		deleteFlag = "delete";
	}
}
function removeFadeIn(){
	if ($('.modal-backdrop.fade.in').length > 0) {
		$('.modal-backdrop.fade.in').remove();
	}
}
function monthChange(index, value){
	var nowDate;
	if(flagDate){
		var x = 0;
		if(value) {
			x += value;
		}
		nowDate = flagDate;
		nowDate = new Date(nowDate.getFullYear() + x, index-1, nowDate.getDate());
	}else {
		nowDate = getSystemTime();
	}
	month = date2String(nowDate);
	flagDate = nowDate;
	$("#showMonth").html();
	$("#dayList").empty();
	var monthDate = stringToDate(month);
	/*老day*/
	var maxDay = new Date(monthDate.getFullYear(), monthDate.getMonth()+1, 0).getDate();
	var firstDay = new Date(monthDate.getFullYear(), monthDate.getMonth(), 1).getDay();
    var $ul = $("#dayList");
    var $li = $('<ul style="margin-bottom: 3px; padding: 0;">').appendTo($ul);
    var a = new Array("日", "一", "二", "三", "四", "五", "六");
    $('<li class="dayLi" style="padding-top: 22px;width:131px;color: #268AED;">' +nowDate.getFullYear() + '<img src="static/images/last.png" style="margin-top: -10px;cursor:pointer;" onclick="monthChange(' + (nowDate.getMonth()+1) + ',-1);">' + 
			  '<img src="static/images/next.png" style="margin-top: 5px;margin-left: -14px;cursor:pointer;" onclick="monthChange(' + (nowDate.getMonth()+1) + ',1);">年'+ selectMonth +'</li>').appendTo($li);
    for(var i=1; i <= maxDay; i++){
    	if (nowDate.getFullYear() < getSystemTime().getFullYear() || (nowDate.getMonth()+1) < (getSystemTime().getMonth() + 1)) {
    		$('<li class="dayLi" onclick="showDay('+ i +',\''+ month +'\', '+  (parseInt(nowDate.getMonth())+1) +')">'
        			+ '<span id="li'+ i +'">'+ a[(firstDay+i-1)%7] +'</span><br>'
        			+'<span class="daySpan" id="span'+ i +'">' + i +'</span></li>').appendTo($li);
    	} else if (nowDate.getFullYear() == getSystemTime().getFullYear() && (nowDate.getMonth()+1) == (getSystemTime().getMonth() + 1)) {
    		if (i <= monthDate.getDate()) {
    			$('<li class="dayLi" onclick="showDay('+ i +',\''+ month +'\', '+  (parseInt(nowDate.getMonth())+1) +')">'
        			+ '<span id="li'+ i +'">'+ a[(firstDay+i-1)%7] +'</span><br>'
        			+'<span class="daySpan" id="span'+ i +'">' + i +'</span></li>').appendTo($li);
    		} else {
    				$('<li class="dayLi">'
					+ '<span style="color: #CCC">'+ a[(firstDay+i-1)%7] +'</span><br>'
					+'<span style="color: #CCC">' + i +'</span></li>').appendTo($li);
    		}
    	} else {
    		$('<li class="dayLi">'
					+ '<span style="color: #CCC">'+ a[(firstDay+i-1)%7] +'</span><br>'
					+'<span style="color: #CCC">' + i +'</span></li>').appendTo($li);
    	}
    }
    showDay(monthDate.getDate(), month, nowDate.getMonth() + 1);
}
/*日期插件*/
function showDay(index, date, monthDefault){
	$("#showMonth").val(monthDefault);
	$('.activeLi').removeClass("activeLi");
	$('.daySpan').removeClass("activeSpan");
	$("#li"+ index).addClass("activeLi");
	$("#span"+ index).addClass("activeSpan");
	var nowDate = stringToDate(date);
	nowDate.setDate(index);
	$("#startChargingTime").val(date2String(nowDate) + " 00:00:00");
	$("#endChargingTime").val(date2String(nowDate) + " 23:59:59");
	search();
}
function autoComplete(autoCompleteID, array, callback, selectID){
	$("#" + autoCompleteID).autocomplete({
		source: array,
		minLength: 0,
		select: function(event, ui){
			if (ui && ui.item && ui.item.ID >= 0) {
				if (selectID) {
					$("#" + selectID).val(ui.item.ID);
				}
				if (typeof callback === 'function') {
					callback();
				}
			}
		}
	});
}
function bindInput(ID, callback){
	$('#' + ID).bind('input propertychange', function() {  
		if (typeof callback === 'function') {
			callback();
		}
	});
}
function escapeRegex(value){
	return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}
function filter(array, term){
	var matcher = new RegExp(escapeRegex(term), "i");
	return $.grep(array, function(value) {
		return matcher.test(value) || matcher.test(value && value.label) ||
		matcher.test(value && value.value) || matcher.test(value && value.ID);
	});
}